﻿using System;
using System.Diagnostics.Contracts;

namespace O1.IO
{
    [ContractVerification(true)]
    internal static class BufferCache8K
    {
        public const int Size = 1024 * 8;

        [ThreadStatic]
        private static byte[] cachedInstance;

        public static byte[] Acquire()
        {
            Contract.Ensures(Contract.Result<byte[]>() != null);
            Contract.Ensures(Contract.Result<byte[]>().Length == Size);

            var buffer = cachedInstance;
            if (buffer != null)
            {
                cachedInstance = null;

                Contract.Assume(buffer.Length == Size);
                return buffer;
            }

            return new byte[Size];
        }

        public static void Release(this byte[] buffer)
        {
            Contract.Requires(buffer != null);
            Contract.Requires(buffer.Length == Size);

            cachedInstance = buffer;
        }
    }
}
